﻿using System.IO;
using System.IO.IsolatedStorage;
using System.Text;
using System.Xml.Linq;
using Agtrix.Utility.Silverlight.Serialization;
using System.ComponentModel;
using System.Windows;

namespace DeepEarth.Core.Persistence
{
	public class PersistStore
	{
		XElement storageRoot;

		public PersistStore()
		{
			Clear();
		}

		public void Clear()
		{
			storageRoot = new XElement("StorageRoot");
		}

		const string IS_FILE_NAME = "DeepEarth.Toolkit.Controls.PersistedState";

		public void Load()
        {
            if (Application.Current.RootVisual != null && DesignerProperties.IsInDesignTool)// DesignerProperties.GetIsInDesignMode(Application.Current.RootVisual))
            {
                return;
            }

            if (IsolatedStorageFile.IsEnabled)
            {
                using (var iStream = new IsolatedStorageFileStream(IS_FILE_NAME, FileMode.OpenOrCreate, IsolatedStorageFile.GetUserStoreForApplication()))
                using (var mStream = new MemoryStream())
                {
                    try
                    {
                        var buf = new byte[1 << 12];
                        int nRead;
                        while ((nRead = iStream.Read(buf, 0, buf.Length)) > 0)
                            mStream.Write(buf, 0, nRead);

                        buf = mStream.ToArray();
                        if (buf.Length == 0)
                            return;
                        buf = buf.Decompress();
                        if (buf.Length == 0)
                            return;

                        string text = Encoding.UTF8.GetString(buf, 0, buf.Length);
                        storageRoot = XElement.Parse(text);
                    }
                    catch
                    {
                        Clear();
                    }
                }
            }
		}

		public void Save()
		{
            if (IsolatedStorageFile.IsEnabled)
            {
                using (var oStream = new IsolatedStorageFileStream(IS_FILE_NAME, FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication()))
                {
                    var data = Encoding.UTF8.GetBytes(storageRoot.ToString());
                    byte[] c = data.Compress();
                    oStream.Write(c, 0, c.Length);
                    oStream.Close();
                }
            }
		}

		public string this[string name, string property]
		{
			get
			{
				if (name == null)
					name = "";
				if (property == null)
					property = "";

				var sub = storageRoot.Element(name);
				if (sub == null)
					return null;
				var vs = sub.Element(property);
				if (vs == null)
					return null;
				var vt = vs.FirstNode as XText;
				return vt.Value;
			}
			set 
			{
                if (value == null)
                {
                    return;
                }

				if (name == null)
					name = "";
				if (property == null)
					property = "";

				bool remove = string.IsNullOrEmpty(value.Trim());

				var sub = storageRoot.Element(name);
				if (sub == null)
				{
					if (remove)
						return;
					sub = new XElement(name);
					storageRoot.Add(sub);
				}

				var vs = sub.Element(property);
				if (vs == null)
				{
					if (remove)
						return;
					var vt = new XText(value);
					vs = new XElement(property, vt);
					sub.Add(vs);
				}
				else
				{
					if (remove)
					{
						vs.Remove();
						if (!sub.HasElements)
							sub.Remove();
					}
					else
					{
						var vt = vs.FirstNode as XText;
						vt.Value = value;
					}
				}

                Save();
                
			}
		}
	}
}
